import logging
import logging.handlers

import datetime

from common.public_util import get_opject_path, read_config_file


class LoggerUtil:

    def create_log(self, logger_name='lOG'):
        #创建一个文件日志对象
        self.logger=logging.getLogger(logger_name)
        #设置文件全局日志级别
        self.logger.setLevel(logging.INFO)
        #防止日志重复
        if not self.logger.handlers:
            #获得日志文件名称
            self.file_log_path=get_opject_path()+ '/logs/' + read_config_file('log','log_name')#read_config_file('log','log_name'
            #创建文件日志控制器
            self.handler=logging.handlers.TimedRotatingFileHandler(self.file_log_path,when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
            self.fromatter=logging.Formatter(read_config_file('log','log_format'))
            #设置文件日志级别
            file_log_lever=str(read_config_file('log','log_level')).lower()
            if file_log_lever== 'debug':
                self.handler.setLevel(logging.DEBUG)
            if file_log_lever == 'info':
                self.handler.setLevel(logging.INFO)
            if file_log_lever == 'warning':
                self.handler.setLevel(logging.WARNING)
            if file_log_lever == 'error':
                self.handler.setLevel(logging.ERROR)
            if file_log_lever == 'critical':
                self.handler.setLevel(logging.CRITICAL)
            self.handler.setFormatter(self.fromatter)
            self.logger.addHandler(self.handler)

            '''设置一个console日志级别'''
            self.console=logging.StreamHandler()
            #设置控制台日志日志级别
            console_log_lever=str(read_config_file('log', 'log_level')).lower()
            if console_log_lever== 'debug':
                self.console.setLevel(logging.DEBUG)
            if console_log_lever == 'info':
                self.console.setLevel(logging.INFO)
            if console_log_lever == 'warning':
                self.console.setLevel(logging.WARNING)
            if console_log_lever == 'error':
                self.console.setLevel(logging.ERROR)
            if console_log_lever == 'critical':
                self.console.setLevel(logging.CRITICAL)
            self.console.setFormatter(logging.Formatter(fmt="[%(asctime)s]-[%(filename)s] %(funcName)s line:%(lineno)d [%(levelname)s]: %(message)s",datefmt="%Y-%m-%d %H:%M:%S"))
            self.logger.addHandler(self.console)
        return self.logger



def write_loging(lognname) :
    LoggerUtil().create_log().info(lognname)

def error_loging(lognname):
    LoggerUtil().create_log().error(lognname)
    Exception(lognname)

if __name__=='__main__':
    write_loging('cesd')
    error_loging('cesjo123')



